package com.atguiguNIO.selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;


/**
 *
 *  Selector 使用 骨架
 *
 * */
public class SelectorSketch {

    public static void main(String[] args) throws IOException {
        //创建selector
        Selector selector = Selector.open();

        //通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        //非阻塞
        serverSocketChannel.configureBlocking(false);

        //绑定连接
        serverSocketChannel.bind(new InetSocketAddress(8086));

        //将通道注册到选择器上
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        //查询已经就绪通道操作
        Set<SelectionKey> selectionKeys = selector.selectedKeys();
        //遍历集合
        Iterator<SelectionKey> iterator = selectionKeys.iterator();
        while (iterator.hasNext()) {
            SelectionKey key = iterator.next();
            //判断key就绪状态操作
            if (key.isAcceptable()) {
                // a connection was accepted by a ServerSocketChannel.
                System.out.println("INFO    key.isAcceptable()    ");
            } else if (key.isConnectable()) {
                System.out.println("INFO  key.isConnectable()"  );
                // a connection was established with a remote server.

            } else if (key.isReadable()) {
                System.out.println("INFO  key.isReadable()");
                // a channel is ready for reading

            } else if (key.isWritable()) {
                System.out.println("INFO  key.isWritable()");
                // a channel is ready for writing

            }
            iterator.remove();
        }


    }
}
